import { login } from '../api';

export default {
  state: {
    userInfo: null
  },
  getters: {
    userInfo: state => state.userInfo
  },
  mutations: {
    setUserInfo(state, user) {
      state.userInfo = user;
      localStorage.setItem('userInfo', JSON.stringify(user));
    }
  },
  actions: {
    /**
     * 登录接口
     * @param data 提交到接口的数据
     * **/
    handleLogin({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data)
          .then(res => {
            //登录成功业务逻辑
            const { errorcode, nurseinfo: userInfo } = res;
            if (errorcode === 0) {
              commit('setUserInfo', userInfo);
              localStorage.setItem('userInfo', JSON.stringify(userInfo));
            }
            resolve(res);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    /**
     * 退出
     * **/
    handleLogout({ commit }) {
      commit('setUserInfo', null);
      localStorage.removeItem('userInfo');
    }
  }
};
